import { ref } from 'vue'
import { defineStore } from 'pinia' 
import { login } from '@/api/index' 
import { setItem, getItem, removeItem } from '@/utils/storage' 

export const useUserStore = defineStore('users', () => { 

    
    const token = ref(getItem('token') || '')
    const userInfo =  ref(getItem('userInfo') || '')
 

    const userLogin = async (userInfo) => { 
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({
          account:username,
          password
        }).then(data => {       
            token.value = data.userinfo.token
            userInfo.value = data.userinfo
            setItem('token', data.userinfo.token)    
            setItem('userInfo', data.userinfo)    
            resolve()
          })
          .catch(err => {
            console.log('eeee',err)
            reject(err)
          })
      })
    } 

    const clearToken = () => {
      token.value = ''
      userInfo.value = ''
      removeItem('token')
      removeItem('resultData')
      removeItem('userInfo')
    }
      
  return { userLogin, userInfo, token,clearToken }
})
